<?php

/**
 * This is the model class for table "attendance".
 *
 * The followings are the available columns in table 'attendance':
 * @property string $attendance_id
 * @property string $workshift_id
 * @property string $user_id
 * @property string $date
 * @property integer $is_present
 * @property integer $is_paid_leave
 * @property string $description
 */
Yii::import('user.models.User');

class Attendance extends CActiveRecord
{

    public $selected_one = 0;
    public $selected_two = 0;
    public $selected_three = 0;
    private $_workshifts;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Attendance the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return 'attendance';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('is_present, is_paid_leave', 'numerical', 'integerOnly' => true),
            array('workshift_id, user_id, date', 'length', 'max' => 10),
            array('description', 'safe'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('attendance_id, workshift_id, user_id, date, is_present, is_paid_leave, description', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'workshift' => array(self::BELONGS_TO, 'Workshift', 'workshift_id'),
            'user' => array(self::BELONGS_TO, 'User', 'user_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'attendance_id' => 'Attendance',
            'workshift_id' => 'Workshift',
            'user_id' => 'User',
            'date' => 'Date',
            'is_present' => 'Is Present',
            'is_paid_leave' => 'Is Paid Leave',
            'description' => 'Description',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('attendance_id', $this->attendance_id, true);
        $criteria->compare('workshift_id', $this->workshift_id, true);
        $criteria->compare('user_id', $this->user_id, true);
        $criteria->compare('date', $this->date, true);
        $criteria->compare('is_present', $this->is_present);
        $criteria->compare('is_paid_leave', $this->is_paid_leave);
        $criteria->compare('description', $this->description, true);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function getAttendanceByDate($date = 0)
    {
        $criteria = new CDbCriteria;
        if ($date != 0) {
            $criteria->addCondition("date=" . $date);
            $criteria->group = "user_id";
        }

        $result = $this->with('user')->findAll($criteria);

        if ($result == null) {
            $models = array();
            $users = User::model()->findAll();
            foreach ($users as $user) {
                //insert dummy data for 3 workshift per each user
                for ($i = 1; $i <= 3; $i++) {
                    $model = new Attendance;
                    $model->user_id = $user->id;
                    $model->workshift_id = $i;
                    $model->date = $date;
                    $model->save();
                }
            }
            $result = $this->with('user')->findAll($criteria);
        }

        $all = $this->_getAllAttendanceByDate($date);

        foreach ($result as &$row) {
            foreach ($all as $record) {
                if ($record->user_id == $row->user_id) {
                    switch ($record->workshift_id) {
                        case 1:
                            $row->selected_one = $this->_getSelectedValue($record);
                            break;
                        case 2:
                            $row->selected_two = $this->_getSelectedValue($record);
                            break;
                        case 3:
                            $row->selected_three = $this->_getSelectedValue($record);
                            break;
                    }
                }
            }
        }

        //default workshift
        $dws = Profile::model()->findAll();
        foreach ($result as &$row) {
            //description == done means admin has already mark attendance
            //otherwise system will load default options from user's profile
            if ($row->description != "done") {
                foreach ($dws as $record) {
                    if ($record->user_id == $row->user_id) {
                        $default = array();
                        if (!empty($record->default_workshift)) {
                            $default = explode(',', $record->default_workshift);
                        }
                        $row->selected_one = (in_array('1', $default)) ? 1 : null;
                        $row->selected_two = (in_array('2', $default)) ? 1 : null;
                        $row->selected_three = (in_array('3', $default)) ? 1 : null;
                    }
                }
            }
        }


        return $result;
    }

    private function _getAllAttendanceByDate($date = 0)
    {
        $criteria = new CDbCriteria;
        if ($date != 0) {
            $criteria->addCondition("date=" . $date);
        }

        $result = $this->findAll($criteria);

        return $result;
    }

    //fix bug --> === '1'
    private function _getSelectedValue($row)
    {
        $ret = null;
        if ($row->is_present) {
            $ret = 1;
        } else {
            if ($row->is_paid_leave === '1') {
                $ret = 2;
            } elseif ($row->is_paid_leave === '0') {
                $ret = 3;
            }
        }
        return $ret;
    }

    public function getDay()
    {
        if ($this->date != null) {
            return date('d', $this->date);
        }
        return 0;
    }

    /**
     * 
     * unix timestamp
     * @param int $date 
     * @return type
     */
    public function getAttendanceDetail($date)
    {
        $criteria = new CDbCriteria;
        $month = date('m');
        //first day in month
        $begin = strtotime(date('Y-m-01'));
        //last day in month
        $end = strtotime(date('Y-m-t'));
        $criteria->addCondition("date >= " . $begin);
        $criteria->addCondition("date <= " . $end);


        $attendances = $this->with('user')->with('workshift')->findAll($criteria);
        $users = User::model()->findAll();
        $result = array();

        $last_day_in_month = (int) date('t');
        foreach ($users as $user) {
            for ($i = 1; $i <= $last_day_in_month; $i++) {
                $row = new AttendanceRow;
                $result[$user->id][$i] = $row;
                $row->date = mktime(0, 0, 0, $month, $i);
            }
        }

        foreach ($attendances as $att) {
            /* @var $att Attendance */
            $day = $att->getDay();
            $row = $result[$att->user_id][$day];
            $value = $att->_getSelectedValue($att);
            $detail = "";

            //values are in combobox
            switch ($value) {
                case 0:
                    break;
                case 1:
                    $detail = substr($att->workshift->title, 0, 1) . ':' . UserModule::t('Present Short', array(), 'attendance');
                    break;
                case 2:
                    $detail = substr($att->workshift->title, 0, 1) . ':' . UserModule::t('Paid Leave Short', array(), 'attendance');
                    break;
                case 3:
                    $detail = substr($att->workshift->title, 0, 1) . ':' . UserModule::t('Un Paid Leave Short', array(), 'attendance');
                    break;
            }
            if ($detail != "") {
                $row->attendanceDetails[] = $detail;
            }
        }
        return $result;
    }

    public function getAttendanceReport($date)
    {
        $criteria = new CDbCriteria;

        $month = date('m', $date);
        $year = date('Y', $date);
        //first day in month
        $begin = mktime(0, 0, 0, $month, 01, $year);
        //last day in month
        $end = mktime(0, 0, 0, $month + 1, 0, $year);
        //$end = strtotime(date('Y-m-t'));

        $criteria->addCondition("date >= " . $begin);
        $criteria->addCondition("date <= " . $end);


        $attendances = $this->with('user')->with('workshift')->findAll($criteria);
        $users = User::model()->findAll();
        $result = array();

        $workshifts = $this->getWorkshifts();

        $ws_ids = array();
        foreach ($users as $user) {
            $result[$user->id]['id'] = $user->id;
            $result[$user->id]['name'] = $user->getName();
            $row = new AttendanceRow;
            foreach ($workshifts as $ws) {
                $row->present[$ws->workshift_id] = 0;
                $row->paid[$ws->workshift_id] = 0;
                $row->unpaid[$ws->workshift_id] = 0;
                $result[$user->id]['summary'] = $row;
                $ws_ids[] = $ws->workshift_id;
            }
        }
        foreach ($attendances as $att) {
            /* @var $att Attendance */
            $row = $result[$att->user_id]['summary'];

            $value = $att->_getSelectedValue($att);

            //values are in combobox
            switch ($value) {
                case 0:
                    break;
                case 1:
                    $row->present[$att->workshift->workshift_id]++;
                    $row->total_paid += $att->workshift->wage;
                    break;
                case 2:
                    $row->paid[$att->workshift->workshift_id]++;
                    $row->total_paid += $att->workshift->wage;
                    break;
                case 3:
                    $row->unpaid[$att->workshift->workshift_id]++;
                    break;
            }
        }
        return $result;
    }

    public function getReportDetailOfUser($month, $year, $user_id)
    {
        $criteria = new CDbCriteria;

        $begin = mktime(0, 0, 0, $month, 01, $year);
        //last day in month
        $end = mktime(0, 0, 0, $month + 1, 0, $year);
        $criteria->addCondition("date >= " . $begin);
        $criteria->addCondition("date <= " . $end);
        $criteria->addCondition("user_id = " . $user_id);

        $attendances = $this->with('user')->with('workshift')->findAll($criteria);
        $workshifts = $this->getWorkshifts();
        $row = new AttendanceRow;

        foreach ($workshifts as $ws) {
            $ws_id = $ws->workshift_id;
            $row->present[$ws_id] = 0;
            $row->paid[$ws_id] = 0;
            $row->unpaid[$ws_id] = 0;
            $row->paid_detail[$ws_id] = 0;
        }
        foreach ($attendances as $att) {
            $value = $att->_getSelectedValue($att);
            //values are in combobox
            $ws_id = $att->workshift->workshift_id;

            switch ($value) {
                case 0:
                    break;
                case 1:
                    $row->present[$ws_id]++;
                    $row->paid_detail[$ws_id] += $att->workshift->wage;
                    break;
                case 2:
                    $row->paid[$ws_id]++;
                    $row->paid_detail[$ws_id] += $att->workshift->wage;
                    break;
                case 3:
                    $row->unpaid[$ws_id]++;
                    break;
            }
        }

        return $row;
    }

    public function getWorkshifts()
    {
        if (is_null($this->_workshifts)) {
            $this->_workshifts = Workshift::model()->findAll();
        }
        return $this->_workshifts;
    }

    public function getNumberOfWorkShifts($user_id, $date)
    {
        $criteria = new CDbCriteria;
        $month = date('m', $date);
        $year = date('Y', $date);
        //first day in month
        $begin = mktime(0, 0, 0, $month, 01, $year);
        //last day in month
        $end = mktime(0, 0, 0, $month + 1, 0, $year);

        $criteria->addCondition('user_id=' . $user_id);
        $criteria->addCondition("date >= " . $begin);
        $criteria->addCondition("date <= " . $end);

        $attendances = $this->with('workshift')->findAll($criteria);

        $totalWorkShifts = 0;

        foreach ($attendances as $att) {
            $value = $this->_getSelectedValue($att);
            if ($value == 1 || $value == 2) {
                $totalWorkShifts++;
            }
        }
        return $totalWorkShifts;
    }

}